package com.butuh.uang.tuh.ang.ui;

import android.annotation.SuppressLint;
import android.os.Build;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;

import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.material.navigation.NavigationView;
import androidx.drawerlayout.widget.DrawerLayout;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.android.installreferrer.api.InstallReferrerClient;
import com.android.installreferrer.api.InstallReferrerStateListener;
import com.android.installreferrer.api.ReferrerDetails;
import com.bumptech.glide.Glide;
import com.butuh.uang.tuh.ang.R;
import com.butuh.uang.tuh.ang.adapter.HomeListAdapter;
import com.butuh.uang.tuh.ang.adapter.HomeListEasyAdapter;
import com.butuh.uang.tuh.ang.adapter.ZhaoHuiAdapter;
import com.butuh.uang.tuh.ang.listener.OnClickDownListener;
import com.butuh.uang.tuh.ang.listener.OnClickNextListener;
import com.butuh.uang.tuh.ang.model.BeannerResult;
import com.butuh.uang.tuh.ang.model.EventDialog;
import com.butuh.uang.tuh.ang.model.HomeListBean;
import com.butuh.uang.tuh.ang.model.ProductDetailBean;
import com.butuh.uang.tuh.ang.present.PMain;
import com.butuh.uang.tuh.ang.util.ConfigData;
import com.butuh.uang.tuh.ang.util.DownLoadUtil;
import com.butuh.uang.tuh.ang.util.FaceBookShareUtils;
import com.butuh.uang.tuh.ang.util.JsonUtils;
import com.butuh.uang.tuh.ang.util.OnClickLogUtils;
import com.butuh.uang.tuh.ang.util.ShareUtil;
import com.butuh.uang.tuh.ang.util.ShatsAppShareUtils;
import com.butuh.uang.tuh.ang.widget.MyGridView;
import com.butuh.uang.tuh.ang.widget.NoScrollListView;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.google.android.gms.ads.identifier.AdvertisingIdClient;
import com.google.android.gms.common.GooglePlayServicesNotAvailableException;
import com.google.android.gms.common.GooglePlayServicesRepairableException;
import com.google.firebase.analytics.FirebaseAnalytics;
import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.iid.InstanceIdResult;
import com.jaeger.library.StatusBarUtil;
import com.lanren.easydialog.DialogViewHolder;
import com.lanren.easydialog.EasyDialog;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;

import butterknife.BindView;
import butterknife.OnClick;
import cn.droidlover.xdroidmvp.kit.Kits;
import cn.droidlover.xdroidmvp.log.XLog;
import cn.droidlover.xdroidmvp.mvp.XActivity;
import cn.droidlover.xdroidmvp.router.Router;

public class MainActivity extends XActivity<PMain> implements AdapterView.OnItemClickListener, OnClickDownListener, FacebookCallback {
    @BindView(R.id.navigation_view)
    NavigationView mNavigation;

    @BindView(R.id.drawer_layout)
    DrawerLayout mDrawerLayout;

    @BindView(R.id.sc)
    ScrollView sc;

    @BindView(R.id.lv_list)
    NoScrollListView mLvList;

    @BindView(R.id.iv_banner)
    ImageView mIvBanner;
    @BindView(R.id.iv_type_1)
    ImageView mIvType1;
    @BindView(R.id.tv_type_1)
    TextView mTvType1;
    @BindView(R.id.iv_type_2)
    ImageView mIvType2;
    @BindView(R.id.tv_type_2)
    TextView mTvType2;

    @BindView(R.id.layout_con_lv)
    LinearLayout mLayoutConLv;

    HomeListAdapter mAdapter;
    HomeListEasyAdapter mEasyAdapter;

    int index = 1;

    @BindView(R.id.layout_data)
    LinearLayout mLayoutData;
    @BindView(R.id.layout_no_net)
    LinearLayout mLayoutNoNet;
    @BindView(R.id.layout_error)
    LinearLayout mLayoutError;
    @BindView(R.id.tv_error_message)
    TextView mTvErrorMessage;

    BeannerResult.DatumBean datumBean = null;

    @BindView(R.id.tv_lv_bottom_message)
    TextView mTvLvBottomMessage;

    boolean isNew = false;
    InstallReferrerClient referrerClient = null;

    boolean isFirst = true;
    @BindView(R.id.iv_to_top)
    ImageView mIvToTop;


    private FirebaseAnalytics mFirebaseAnalytics;



    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    public void initData(Bundle savedInstanceState) {
        EventBus.getDefault().register(this);
        isFirst = true;
        StatusBarUtil.setTranslucentForImageView(this, 0, null);
        ViewGroup.LayoutParams layoutParams = mNavigation.getLayoutParams();
        layoutParams.width = Kits.Dimens.getDisplayWidth(context) / 5 * 3;
        mNavigation.setLayoutParams(layoutParams);
        mAdapter = new HomeListAdapter(this, this);
        mLvList.setAdapter(mAdapter);
        mEasyAdapter = new HomeListEasyAdapter(this);
        mLvList.setOnItemClickListener(this);
        mDialog.Show();
        getHomeList();
        installReferrerClient();
        mIvToTop.setVisibility(View.GONE);
        sc.setOnScrollChangeListener(new View.OnScrollChangeListener() {
            @Override
            public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                if (scrollY == 0) {
                    mIvToTop.setVisibility(View.GONE);
                } else {
                    mIvToTop.setVisibility(View.VISIBLE);
                }
            }
        });

    }


    /***
     * 归因
     */
    public void installReferrerClient() {
        if (null == referrerClient) {
            referrerClient = InstallReferrerClient.newBuilder(this).build();
        }
        referrerClient.startConnection(new InstallReferrerStateListener() {
            @Override
            public void onInstallReferrerSetupFinished(int responseCode) {
                String referrer = "";
                XLog.e("======responseCode=====" + responseCode);
                switch (responseCode) {
                    case InstallReferrerClient.InstallReferrerResponse.OK:
                        XLog.e("======InstallReferrerResponse.OK=====");
                        if (referrerClient != null) {
                            try {
                                ReferrerDetails response = referrerClient.getInstallReferrer();
                                referrer = response.getInstallReferrer();// 你要得referrer值
                                referrerClient.endConnection();
                            } catch (Exception ex) {
                                referrer = "";
                                Log.e("InstallReferrerHelper", ex.toString());
                            }
                            getGoogleAdvertiseId(referrer);
                        }
                        // Connection established.
                        break;
                    case InstallReferrerClient.InstallReferrerResponse.FEATURE_NOT_SUPPORTED:
                        // API not available on the current Play Store app.
                        XLog.e("======InstallReferrerResponse.FEATURE_NOT_SUPPORTED=====");
                        referrer = "";
                        getGoogleAdvertiseId(referrer);
                        break;
                    case InstallReferrerClient.InstallReferrerResponse.SERVICE_UNAVAILABLE:
                        // Connection couldn't be established.
                        XLog.e("======InstallReferrerResponse.SERVICE_UNAVAILABLE=====");
                        referrer = "";
                        getGoogleAdvertiseId(referrer);
                        break;
                }
            }

            @Override
            public void onInstallReferrerServiceDisconnected() {
                XLog.e("======onInstallReferrerServiceDisconnected=====");
                // Try to restart the connection on the next request to
                // Google Play by calling the startConnection() method.
            }
        });
    }

    //获取Google广告ID
    public void getGoogleAdvertiseId(final String referrer) {
        Executors.newSingleThreadExecutor().execute(new Runnable() {
            @Override
            public void run() {
                AdvertisingIdClient.Info info = null;
                String advertisingId = "";
                try {
                    info = AdvertisingIdClient.getAdvertisingIdInfo(MainActivity.this);
                    advertisingId = info.getId();
                    getAnalyticsToken(referrer, advertisingId);
                } catch (IOException e) {
                    e.printStackTrace();
                    advertisingId = "";
                    getAnalyticsToken(referrer, advertisingId);
                } catch (GooglePlayServicesNotAvailableException e) {
                    e.printStackTrace();
                    XLog.e("======GooglePlayServicesNotAvailableException=====" + e.toString());
                    advertisingId = "";
                    getAnalyticsToken(referrer, advertisingId);
                } catch (GooglePlayServicesRepairableException e) {
                    e.printStackTrace();
                    XLog.e("======GooglePlayServicesRepairableException=====" + e.toString());
                    advertisingId = "";
                    getAnalyticsToken(referrer, advertisingId);
                }

            }
        });
    }


    @SuppressLint("MissingPermission")
    public void getAnalyticsToken(String referrer, String advertisingId) {
//        FirebaseInstanceId.getInstance().getInstanceId().addOnSuccessListener( MainActivity.this,  new OnSuccessListener<InstanceIdResult>() {
//            @Override
//            public void onSuccess(InstanceIdResult instanceIdResult) {
//                String newToken = instanceIdResult.getToken();
//                XLog.e("=====newToken",newToken);
//            }
//        }).addOnFailureListener(MainActivity.this, new OnFailureListener() {
//            @Override
//            public void onFailure(@NonNull Exception e) {
//                XLog.e("=====newToken==="+e.toString());
//            }
//        });
//        if (null == mFirebaseAnalytics) {
//            mFirebaseAnalytics = FirebaseAnalytics.getInstance(this);
//        }
//        getP().setdeviceinfo(this, referrer, advertisingId, mFirebaseAnalytics.getFirebaseInstanceId());
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onGetMessage(EventDialog message) {
        mDialog.Dismiss();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (isFirst) {
            isFirst = false;
            mDialog.Show();
        } else {
            mDialog.Dismiss();
        }
        if (isNew) {
            isNew = false;
            getP().getNewList();
        }
    }


    public void getHomeList() {
        mDialog.Show();
        getP().getHomeList();
    }

    public void getEasyList() {
        List<String> map = new ArrayList<>();
        map.add(ConfigData.PAGE_NAME_HOME_EASY);
        OnClickLogUtils.onClickLog(this, "come-in-into", JsonUtils.getRequestBody(map), 0);
        mDialog.Show();
        getP().getEasyList();
    }


    @OnClick({R.id.iv_mine, R.id.iv_share, R.id.iv_to_top, R.id.layout_type_1, R.id.layout_type_2, R.id.layout_down_history
            , R.id.layout_call_our, R.id.layout_yinsi, R.id.layout_ver, R.id.layout_faq, R.id.tv_resume, R.id.iv_banner})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_mine:
                mDrawerLayout.openDrawer(Gravity.START);
                OnClickLogUtils.onClickPermute(context, ConfigData.PAGE_NAME_HOME, "user", 0);
                break;
            case R.id.iv_to_top:
                sc.scrollTo(0, 0);
                OnClickLogUtils.onClickPermute(context, ConfigData.PAGE_NAME_HOME, "scrollToTop", 0);
                break;
            case R.id.layout_type_1:
                if (1 != index) {
                    index = 1;
                    switchType();
                    OnClickLogUtils.onClickPermute(context, ConfigData.PAGE_NAME_HOME, ConfigData.PAGE_NAME_HOME, 0);
                }
                break;
            case R.id.layout_type_2:
                if (2 != index) {
                    index = 2;
                    switchType();
                    OnClickLogUtils.onClickPermute(context, ConfigData.PAGE_NAME_HOME, ConfigData.PAGE_NAME_HOME_EASY, 0);
                }
                break;
            case R.id.iv_share:
                ShareDialog();
                OnClickLogUtils.onClickPermute(context, ConfigData.PAGE_NAME_HOME, "share", 0);
                break;
            case R.id.tv_resume:
                switchType();
                OnClickLogUtils.onClickPermute(context, ConfigData.PAGE_NAME_HOME, "errorResume", 0);
                break;
            case R.id.layout_down_history:
                Router.newIntent(this).to(DownHistoryActivity.class).launch();
                OnClickLogUtils.onClickPermute(context, ConfigData.PAGE_NAME_HOME, "toDownloadHistory", 0);
                break;
            case R.id.layout_call_our:
                Router.newIntent(this).to(CallOurActivity.class).launch();
                OnClickLogUtils.onClickPermute(context, ConfigData.PAGE_NAME_HOME, "toHubungiKami", 0);
                break;
            case R.id.layout_yinsi:
                Router.newIntent(this).to(YinSiActivity.class).launch();
                OnClickLogUtils.onClickPermute(context, ConfigData.PAGE_NAME_HOME, "toKebijakanPrivasi", 0);
                break;
            case R.id.layout_ver:
                Router.newIntent(this).to(VerActivity.class).launch();
                OnClickLogUtils.onClickPermute(context, ConfigData.PAGE_NAME_HOME, "toVersion", 0);
                break;
            case R.id.layout_faq:
                Router.newIntent(this).to(FAQActivity.class).launch();
                OnClickLogUtils.onClickPermute(context, ConfigData.PAGE_NAME_HOME, "toFaq", 0);
                break;
            case R.id.iv_banner:
                if (null != datumBean) {
                    mDialog.Show();
                    getP().getProductDetail(Integer.parseInt(datumBean.getExt0()));
                    OnClickLogUtils.onClickPermute(context, ConfigData.PAGE_NAME_HOME, "banner", 0);
                }
                break;
        }
    }

    public void loadDataSuccess(ProductDetailBean bean) {
        DownLoadUtil.download(this, "detail", "new", 0, bean.getBianhao(), bean.getPattern(), bean.getOpenMode(), bean.getSite(), bean.getBag());
    }

    public void loadDataFail(String message) {
        getvDelegate().toastShort(message);
        mDialog.Dismiss();
    }


    public void loadNewSuccess(List<HomeListBean> list) {
        showZhaoHuiDialog(list);
    }


    ZhaoHuiAdapter zhaoHuiAdapter;

    private void showZhaoHuiDialog(final List<HomeListBean> list) {
        final List<HomeListBean> mList = new ArrayList<>();
        if (list.size() < 4) {
            mList.addAll(list);
        } else {
            for (int i = 0; i < 3; i++) {
                mList.add(list.get(i));
            }
        }
        zhaoHuiAdapter = new ZhaoHuiAdapter(this);
        new EasyDialog(this, R.layout.dialog_zhaohui) {//设置自己的自定义布局文件
            @Override
            public void onBindViewHolder(DialogViewHolder holder) {
                holder.setOnClick(R.id.iv_close, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dismiss();
                    }
                });
                MyGridView mGv = holder.getView(R.id.gv_data);
                mGv.setNumColumns(mList.size());
                mGv.setAdapter(zhaoHuiAdapter);
                zhaoHuiAdapter.setData(mList);
                mGv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        dismiss();
                        OnClickLogUtils.onClickPermute(context, ConfigData.PAGE_NAME_HOME, "new", position);
                        HomeListBean bean = list.get(position);
                        isNew = false;
                        mDialog.Show();
                        DownLoadUtil.download(MainActivity.this, ConfigData.PAGE_NAME_HOME, "new", position, bean.getBianhao(), bean.getPattern(), bean.getOpenMode(), bean.getSite(), bean.getBag());
                    }
                });
            }
        }.backgroundLight(0.2)
                .setCanceledOnTouchOutside(false)
                .setCancelAble(false)
                .showDialog();
    }

    FaceBookShareUtils faceBookShareUtils = null;

    CallbackManager callBackManager = null;


    private void ShareDialog() {
        new EasyDialog(this, R.layout.dialog_share) {//设置自己的自定义布局文件
            @Override
            public void onBindViewHolder(DialogViewHolder holder) {
                holder.setOnClick(R.id.iv_share_close, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dismiss();

                    }
                });
                holder.setOnClick(R.id.iv_share_facebook, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dismiss();
                        if (null == callBackManager) {
                            callBackManager = CallbackManager.Factory.create();
                        }
                        if (null == faceBookShareUtils) {
                            faceBookShareUtils = new FaceBookShareUtils(MainActivity.this, callBackManager, MainActivity.this);
                        }
                        OnClickLogUtils.onClickPermute(context, ConfigData.PAGE_NAME_HOME, "shareFaceBook", 0);
                        faceBookShareUtils.share(ShareUtil.SHARE_NAME, ShareUtil.SHARE_URL);
                    }
                });
                holder.setOnClick(R.id.iv_share_whatsapp, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dismiss();
                        OnClickLogUtils.onClickPermute(context, ConfigData.PAGE_NAME_HOME, "shareWhatsApp", 0);
                        ShatsAppShareUtils.share(MainActivity.this, ShareUtil.SHARE_URL);
                    }
                });
            }
        }.backgroundLight(0.2)
                .setCanceledOnTouchOutside(false)
                .setCancelAble(false)
                .showDialog();
    }


    public void switchType() {
        sc.scrollTo(0, 0);
        if (index == 1) {
            mIvBanner.setVisibility(View.VISIBLE);
            mIvType1.setImageResource(R.mipmap.tab_home01);
            mIvType2.setImageResource(R.mipmap.tab_mud00);
            mTvType1.setTextColor(getResources().getColor(R.color.color_ff9f19));
            mTvType2.setTextColor(getResources().getColor(R.color.color_cccccc));
            mLvList.setDivider(getResources().getDrawable(R.color.color_train));
            mLvList.setDividerHeight(getResources().getDimensionPixelSize(R.dimen.dp_8));
            mLvList.setAdapter(mAdapter);
            mAdapter.clearData();
            mEasyAdapter.clearData();
            getHomeList();
        } else {
            mIvBanner.setVisibility(View.GONE);
            mIvType1.setImageResource(R.mipmap.tab_home00);
            mIvType2.setImageResource(R.mipmap.tab_mud01);
            mTvType1.setTextColor(getResources().getColor(R.color.color_cccccc));
            mTvType2.setTextColor(getResources().getColor(R.color.color_ff9f19));
            mLvList.setDivider(getResources().getDrawable(R.color.color_cccccc));
            mLvList.setDividerHeight(getResources().getDimensionPixelSize(R.dimen.dp_1));
            mLvList.setAdapter(mEasyAdapter);
            mAdapter.clearData();
            mEasyAdapter.clearData();
            getEasyList();
        }
    }

    int count = 0;

    public void loadList(final List<HomeListBean> list) {
        mDialog.Dismiss();
        if (list.size() != 0) {
            mLayoutData.setVisibility(View.VISIBLE);
            mLayoutNoNet.setVisibility(View.GONE);
            mLayoutError.setVisibility(View.GONE);
            mAdapter.setData(list);
            if (list.size() > 3) {
                mTvLvBottomMessage.setVisibility(View.VISIBLE);
                count = 4;
            } else {
                mTvLvBottomMessage.setVisibility(View.GONE);
                count = list.size();
            }
            getP().getBanner();
        } else {
            mLayoutData.setVisibility(View.GONE);
            mLayoutNoNet.setVisibility(View.GONE);
            mLayoutError.setVisibility(View.VISIBLE);
            mTvErrorMessage.setText("Saat ini tidak ada produk");
        }


        OnClickLogUtils.onClickLog(this, "set-up", "[]", 0, new OnClickNextListener() {
            @Override
            public void clickNext() {
                List<String> map = new ArrayList<>();
                map.add(ConfigData.PAGE_NAME_HOME);
                OnClickLogUtils.onClickLog(MainActivity.this, "come-in-into", JsonUtils.getRequestBody(map), 0, new OnClickNextListener() {
                    @Override
                    public void clickNext() {
                        List<String> mList = new ArrayList<>();
                        mList.add(String.valueOf(mLayoutConLv.getHeight()));
                        mList.add(String.valueOf(list.size()));
                        mList.add(String.valueOf(count));
                        OnClickLogUtils.onClickLog(MainActivity.this, "consume", JsonUtils.getRequestBody(mList), 0, null);
                    }
                });
            }
        });

    }

    public void setBannerSuccess(BeannerResult.DatumBean bean) {
        datumBean = bean;
        if (null != datumBean) {
            Glide.with(this).load(datumBean.getTitleImg01()).into(mIvBanner);
        }

    }

    public void loadEasyList(List<HomeListBean> list) {
        mDialog.Dismiss();
        if (list.size() != 0) {
            mLayoutData.setVisibility(View.VISIBLE);
            mLayoutNoNet.setVisibility(View.GONE);
            mLayoutError.setVisibility(View.GONE);
            mEasyAdapter.setData(list);
            if (list.size() > 6) {
                mTvLvBottomMessage.setVisibility(View.VISIBLE);
            } else {
                mTvLvBottomMessage.setVisibility(View.GONE);
            }
        } else {
            mLayoutData.setVisibility(View.GONE);
            mLayoutNoNet.setVisibility(View.GONE);
            mLayoutError.setVisibility(View.VISIBLE);
            mTvErrorMessage.setText("Saat ini tidak ada produk");
        }
    }

    public void loadListError(int type, String message) {
        mDialog.dismiss();
        if (type == 1) {
            mLayoutData.setVisibility(View.GONE);
            mLayoutNoNet.setVisibility(View.VISIBLE);
            mLayoutError.setVisibility(View.GONE);
        } else {
            mLayoutData.setVisibility(View.GONE);
            mLayoutNoNet.setVisibility(View.GONE);
            mLayoutError.setVisibility(View.VISIBLE);
            mTvErrorMessage.setText(message);
        }
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (mDrawerLayout.isDrawerOpen(Gravity.START)) {
                mDrawerLayout.closeDrawer(Gravity.START);
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    public PMain newP() {
        return new PMain();
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        switch (parent.getId()) {
            case R.id.lv_list:
                if (index == 1) {
                    OnClickLogUtils.onClickPermute(context, ConfigData.PAGE_NAME_HOME, "productlist", 0);
                    Router.newIntent(this).to(ProductDetailActivity.class).putInt("id", mAdapter.getDataSource().get(position).getBianhao()).launch();
                } else if (index == 2) {
                    mDialog.Show();
                    isNew = true;
                    HomeListBean bean = mEasyAdapter.getDataSource().get(position);
                    DownLoadUtil.download(this, ConfigData.PAGE_NAME_HOME_EASY, "producteasylist", position, bean.getBianhao(), bean.getPattern(), bean.getOpenMode(), bean.getSite(), bean.getBag());
                }
                break;
        }
    }

    @Override
    public void download(HomeListBean bean, int position) {
        mDialog.Show();
        isNew = true;
        DownLoadUtil.download(this, ConfigData.PAGE_NAME_HOME, "productlist", position, bean.getBianhao(), bean.getPattern(), bean.getOpenMode(), bean.getSite(), bean.getBag());
    }

    @Override
    public void onSuccess(Object o) {
        XLog.e("------分享成功-----" + o.toString());
    }

    @Override
    public void onCancel() {
        XLog.e("------关闭分享-----");
    }

    @Override
    public void onError(FacebookException error) {
        XLog.e("------分享onError-----");
    }


}
